<?php
//Baokim Payment Notification (BPN) Sample

//Lay thong tin tu Baokim POST sang
$req = '';
foreach ( $_POST as $key => $value ) {
	$value = urlencode ( stripslashes ( $value ) );
	$req .= "&$key=$value";
}

/* thuc hien  ghi log cac tin nhan BPN
$myFile = "bpn.log";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, $req);
*/

$ch = curl_init();

//Dia chi chay BPN test
//curl_setopt($ch, CURLOPT_URL,'http://sandbox.baokim.vn/bpn/verify');

//Dia chi chay BPN that
curl_setopt($ch, CURLOPT_URL,'https://sandbox.baokim.vn/bpn/verify');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
$error = curl_error($ch);

if($result != '' && strstr($result,'VERIFIED') && $status==200){
	//thuc hien update hoa don
	fwrite($fh, ' => VERIFIED');
	
	$order_id = $_POST['order_id'];
	$transaction_id = $_POST['transaction_id'];
	$transaction_status = $_POST['transaction_status'];
	
	//Mot so thong tin khach hang khac
	$customer_name = $_POST['customer_name'];
	$customer_address = $_POST['customer_address'];
	//...
	
	//Nghiep vu: kiem tra xem order_id nay co ton tai trong he thong khong
	
	
	/**
	 * Neu co thi update thong tin thanh toan vao
	 */
	//update thong tin thanh toan
	
	//kiem tra trang thai giao dich
	if ($transaction_status == 13){
		//xac nhan la da thanh toan thanh cong don hang
		echo "thanhcong";
	}
	
	
	/**
	 * Neu khong thi bo qua
	 */
}else{
	fwrite($fh, ' => INVALID');
}

if ($error){
	fwrite($fh, " | ERROR: $error");
}

fwrite($fh, "\r\n");

fclose($fh);